package net.skystudio.es.service.impl;

import net.skystudio.es.dto.MixedOrderDTO;
import net.skystudio.es.elastic.repository.MixedOrderRepository;
import net.skystudio.es.entity.MixedOrder;
import net.skystudio.es.service.MixedOrderService;
import org.elasticsearch.index.query.MatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 混合订单服务层
 */
@Service
public class MixedOrderServiceImpl implements MixedOrderService {

    @Autowired
    private MixedOrderRepository mixedOrderRepository;

    @Override
    public long count() {
        return mixedOrderRepository.count();
    }

    @Override
    public MixedOrder save(MixedOrder mixedOrder) {
        return mixedOrderRepository.save(mixedOrder);
    }

    @Override
    public void delete(MixedOrder mixedOrder) {
        mixedOrderRepository.delete(mixedOrder);
    }

    @Override
    public Iterable<MixedOrder> getAll() {
        return mixedOrderRepository.findAll();
    }

    @Override
    public List<MixedOrder> getByGoodsInfo(String goodsInfo) {
        List<MixedOrder> result = new ArrayList<>();
        MatchQueryBuilder matchQueryBuilder = new MatchQueryBuilder("goodsInfo", goodsInfo);
        Iterable<MixedOrder> iterable  = mixedOrderRepository.search(matchQueryBuilder);
        iterable.forEach(e -> result.add(e));
        return result;
    }

    @Override
    public Page<MixedOrder> pageQuery(Integer page, Integer size, MixedOrderDTO mixedOrderDTO) {
        NativeSearchQuery searchQuery =  new NativeSearchQueryBuilder()
                .withQuery(QueryBuilders.matchPhraseQuery("goodsInfo", mixedOrderDTO.getGoodsInfo()))
                .withPageable(PageRequest.of(page, size))
                .build();
        return mixedOrderRepository.search(searchQuery);
    }

}
